package com.fengye.security.rest;

import com.fengye.security.domain.User;
import com.fengye.security.security.service.UserDetailsServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * @author fengyexjtu@126.com
 * @date 2022年04月11日 7:37 PM
 */

@RestController
@RequestMapping("/api")
@Slf4j
@RequiredArgsConstructor
public class UserResource {

    private final UserDetailsServiceImpl userDetailsService;

    @GetMapping("/greeting")
    public String greeting() {
        log.debug("执行 api -> greeting");
        return "greeting!";
    }

    @GetMapping("/authentication")
    public void getAuthentication(Principal principal, Authentication authentication) {
        log.info("SecurityContextHolder获取Authentication中用户名:{}", SecurityContextHolder.getContext().getAuthentication().getName());
        log.info("SecurityContextHolder获取Authentication对象:{}", SecurityContextHolder.getContext().getAuthentication());
        log.info("SecurityContextHolder获取Principal对象:{}", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        log.info("依赖注入方式获取 principal:{}", principal);
        log.info("依赖注入方式获取 authentication:{}", authentication);
    }

    @GetMapping("/users/{username}")
    public String getCurrentUsername(@PathVariable String username) {
        return username;
    }


    @PostAuthorize("returnObject.username == authentication.name")
    @GetMapping("/user/email/{email_name}")
    public User getUserByEmail(@PathVariable("email_name") String email, Authentication authentication) {
        log.info("Authorities = {}", authentication.getAuthorities());
        return userDetailsService.findOptionalByEmail(email).orElseThrow(() -> new RuntimeException("email 未找到"));
    }

    @PreAuthorize("hasRole('MANAGER')")
    @GetMapping("/manager/resource")
    public String managerResource(Authentication authentication) {
        log.info("Authorities = {}", authentication.getAuthorities());
        return "manager";
    }
}
